﻿$.validator.methods.equal = function (value, element, param) {
    return value == param;
};

$().ready(function () {
    $("#optCategoryPerson").attr("class", "ListSelectedOption");
    $("#breadcrumb").append('<li><a href="' + $("#urlCategoryPerson").val() + '" title="Categoria Persona">Categoria Persona</a></li>');

    $("#optCategoryPerson").attr("class", "ListSelectedOption");
    $("#optDashboard").attr("class", "");
    $("#optGeneral").attr("class", "current");
    $("#optAccounting").attr("class", "");

    var validator = $("#frmCategory").bind("invalid-form.validate", function () {
        $("#lblErrorMsgCategory").show();
    }).validate({
        debug: true,
        rules: {
            txtCategory: {
                required: true,
                minlength: 5
            },
            txtDescription: {
                required: true,
                minlength: 5
            }
        },
        messages: {
            txtCategory: "",
            txtDescription: ""
        }
    });
    $('#btnSearch').click(function () {
        Search();
    });

    $("#txtStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true


    });

    $('#btnClearCategoryForm').live('click', function () {
        ClearCategoryForm();
    });

    $('#btnAddCategory').live('click', function () {
        IsValidCategoryForm();
    });

    $("#lblErrorMsgCategory").hide();
    $("#lblsuccessMsgCategory").hide();

    $("#txtCategory").removeClass("error");
    $("#txtDescription").removeClass("error");


    if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
        InitAutocomplete();
    }
});




function IsValidCategoryForm() {
    if ($("#frmCategory").valid()) {
        $("#lblErrorMsgCategory").hide();
        $("#lblsuccessMsgCategory").hide();
        AddCategory();
    }
}

function AddCategory() {
    $.ajax(
    {
        type: "POST",
        url: "/ODSYSUI/General/AddCategory",
        data:
            JSON.stringify({
                Category: $('#txtCategory').val(),
                Description: $('#txtDescription').val()
            }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                ClearCategoryForm();
                $("#lblsuccessMsgCategory").show(300).delay(5000).hide(400);
            }
            else {
                $("#lblsuccessMsgCategory").hide();
                $("#lblErrorMsgCategory").show();
                $("#frmCategoryErrorMessage").text(result.msg);
            }
        },
        error: function (req, status, error) {
            $("#lblsuccessMsgCategory").hide();
            $("#lblErrorMsgCategory").show();
            $("#frmCategoryErrorMessage").text("An error has occurred. Please contact your administrator.");
        }
    });
}

function ClearCategoryForm() {
    $('#txtCategory').val('');
    $('#txtDescription').val('');

    $("#lblErrorMsgCategory").hide();
    $("#lblsuccessMsgCategory").hide();

    $("#txtCategory").removeClass("error");
    $("#txtDescription").removeClass("error");
}


function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el registro?')) {
        DeleteCategory(id);
    }
}

function DeleteCategory(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/CategoryPerson/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/CategoryPerson/SetMessage?id=2";
        }
    });
 
}






function InitAutocomplete() {
    $("#txtPersonFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {
                    debugger;
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#personID').val(ui.item.ID);
        }
    });

    $("#txtPersonFilter").keyup(function () {
        if (!this.value) {
            $('#personID').val();
        }
    });
}

function Search() {
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                name: $('#txtName').val(),
                startDate: date1,
                endDate: date2,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}